var mongoose = require('mongoose');
var Upload = require('../models/upload.model')// 引数据模型
var path=require('path');
var multer = require('multer');
var fs = require('fs');
var async = require('async');
var base64Img = require('base64-img');//图片转成base64的插件


var storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, './uploads')
	},
	filename: function (req, file, cb) {
		cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
	}
})

exports.upload=function(req,res,next){
	var upload = multer({
		 storage: storage,
		 fileFilter:function(req,file,callback){
            var ext=path.extname(file.originalname);
            if(ext !=='.png' && ext !=='.jpg' && ext !== '.gif'){
            return callback(res.end('文件类型不符合'));
            }
            callback(null,true);
		 } 
    }).single('avatar')
    
    upload(req,res,function(err){
        console.log(res.req.file)
        base64Img.base64('./uploads/'+res.req.file.filename, function(err, data) {//图片转成base64
            res.req.file.dataurl=data;
            res.json(res.req.file);
            res.end('file uploaded');
        })

    })
}



// 新增
exports.create = function(req,res,next){
    var upload = new Upload(req.body); // 从req.body里获取参数对象，比如{name:'vane',gender:'男',city:'杭州'....}

    upload.save()
    .then(data=>{
        res.json(data)
    })
}

exports.getone = function(req,res,next){
    var id = req.params.id;

    Upload.findById(id,function(err,result){
        console.log(result);
        res.json(result)
    })
    
}

exports.getcate = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 9;

    var queryCondition = {};
    var postId;
    if( req.body.postId && req.body.postId.trim().length>0 ){
        postId = req.body.postId;
        queryCondition = {"cateId":postId}
    }

    Upload.paginate(queryCondition, { page: page, limit: limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;

        res.json(result)
    });

}


//删除
exports.remove = function(req,res,next){
    var id = req.body.id;
    Upload.remove({ _id:id})
    .then(data=>{
        res.json({msg:'数据删除成功',status:200})
    });

    var filepath = './uploads/'+req.body.filename;
    fs.unlink(filepath, function(err){
     if(err){
      throw err;
     }
     console.log('文件:'+filepath+'删除成功！');
    })
} 


exports.removes = function(req,res,next){
    var ids = req.body.ids;
    Upload.remove({ _id:{ $in: ids }})
    .then(data=>{
        res.json({msg:'数据删除成功',status:200})
    });

    var fns = req.body.fns;
    async.map(fns,function(item,callback){
        var filepath = './uploads/'+item;
        fs.unlink(filepath, function(err){
         if(err){
          throw err;
         }
         console.log('文件:'+filepath+'删除成功！');
        })
    },function(err,r){

    })
} 

exports.list = function(req,res,next){
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 4;

    var queryCondition = {};
    var cateId;
    if( req.body.title && req.body.title.trim().length>0 ){
        cateId = req.body.cateId;
        queryCondition = {"cateId":new RegExp(cateId,'t')}
    }


    Upload.paginate(queryCondition, { page: page, limit: limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;

       res.json(result)
    });
}


function reverseTree(data,pid){
    var result=[],temp;

    var data= JSON.parse(JSON.stringify(data));

    for(var i in data){
        if(data[i].parentId === pid){
            result.push(data[i]);

            temp = reverseTree(data,data[i]._id);
 
            if(temp.length>0){
                data[i].children = temp;
            }
        }
    }
    return result;
}